package ltd.dujiabao.mavenLocalInstaller.util;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

/**
 * @author : DuJiabao
 * @Project : mavenLocalInstaller
 * @Time : 2021/9/29 22:35
 * @Desc :
 */
public class StreamUtils {
    /**
     * 将输入Reader 输出到控制台
     */
    public static String output(Reader reader) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        return stringBuilder.toString();
    }

    /**
     * 将输入流输出到控制台
     *
     * @param inputStream 输入流
     * @param charset     输入的编码格式
     * @return 返回输出的字符串
     * @throws IOException 需要检查IO异常
     */
    public static String output(InputStream inputStream, String charset) throws IOException {
        InputStreamReader reader = new InputStreamReader(inputStream, charset);
        return output(reader);
    }


    /**
     * 将输入流输出到控制台
     *
     * @param inputStream 输入流
     * @param charset     输入的编码格式
     * @return 返回输出的字符串
     * @throws IOException 需要检查IO异常
     */
    public static String output(InputStream inputStream, Charset charset) throws IOException {
        InputStreamReader reader = new InputStreamReader(inputStream, charset);
        return output(reader);
    }

    public static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
